part of '../index.dart';

class VoiceRecording extends StatefulWidget {
  const VoiceRecording({super.key});

  @override
  State<VoiceRecording> createState() => _VoiceRecordingState();
}

class _VoiceRecordingState extends State<VoiceRecording> {
  final sounder = FlutterSoundRecord();
  String msg = T.current.c_hold_to_talk;
  int seconds = 0;
  Timer? _timer;
  String? _recordPath;
  bool _isCancel = false;

  @override
  void initState() {
    super.initState();
    _permission();
  }

  void _permission() async {
    await sounder.hasPermission();
  }

  void _startTimer() {
    seconds = 0;
    _timer = Timer.periodic(const Duration(seconds: 1), (Timer timer) {
      safeSetState(() {
        seconds++;
      });
    });
  }

  void _stopTimer() {
    _timer?.cancel();
    _timer = null;

  }

  void _start() async {
    final directory = await getApplicationDocumentsDirectory();
    final timestamp = DateTime.now().millisecondsSinceEpoch.toString();
    _recordPath = '${directory.path}/$timestamp.m4a';
    bool hasPermission = await sounder.hasPermission();
    if (!hasPermission) {
      safeSetState(() => msg = 'No microphone permission');
      return;
    }
    try {
      await sounder.start(path: _recordPath);
      safeSetState(() => msg = T.current.c_slide_to_cancel);
      _startTimer();
    } catch (e) {
      safeSetState(() => msg = 'Failed to start recording');
      debugPrint('录音失败: $e');
    }
  }

  void _stop() async {
    _stopTimer();
    final tempSeconds = seconds;
    if (_isCancel) {
      _isCancel = false;
      safeSetState(() {
        seconds = 0;
        msg = T.current.c_hold_to_talk;
      });
      return;
    }
    if (seconds <= 1) {
      EasyLoading.showToast(T.current.c_record_too_short);
      safeSetState(() {
        seconds = 0;
        msg = T.current.c_hold_to_talk;
      });
      return;
    }
    try {
      final path = await sounder.stop();
      safeSetState(() {
        seconds = 0;
        msg = T.current.c_hold_to_talk;
      });
      debugPrint('录音结束，文件路径: $path');
      if (path != null && File(path).existsSync() && mounted) {
        context.read<ChatProvider>().sendVoiceMessage(path, tempSeconds);
      } else {
        debugPrint('录音文件不存在: $path');
        EasyLoading.showToast('录音保存失败');
      }
    } catch (e) {
      safeSetState(() => msg = 'Failed to save recording');
      debugPrint('停止录音失败: $e');
    }
  }

  void _cancel() {
    _stopTimer();
    sounder.stop();
    safeSetState(() {
      msg = T.current.c_hold_to_talk;
      seconds = 0;
    });
    _isCancel = true;
  }

  void safeSetState(VoidCallback fn) {
    if (mounted) {
      setState(fn);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.center,
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Container(
          decoration: const BoxDecoration(
            image: DecorationImage(image: AssetImage(Images.icRipple)),
          ),
          alignment: Alignment.center,
          child: Text(
            '${seconds}s',
            style: const TextStyle(fontSize: 20, color: Color(0xFF444444)),
          ),
        ),
        Padding(
          padding: const EdgeInsets.only(top: 8, bottom: 30),
          child: Text(
            msg,
            style: const TextStyle(color: Color(0xFFC1C1C1)),
          ),
        ),
        GestureDetector(
          onTap: () {},
          onLongPress: _start,
          onLongPressEnd: (details) => _stop(),
          onLongPressMoveUpdate: (details) {
            if (details.offsetFromOrigin.dy < -20) {
              _cancel();
            }
          },
          behavior: HitTestBehavior.translucent,
          child: Image.asset(
            seconds == 0 ? Images.icVoiceNormal : Images.icVoiceActive,
            width: 75,
            height: 75,
          ),
        ),
      ],
    );
  }
}
